#include<iostream>
#include"RingQueue.hpp"
#include"Task.hpp"
#include<pthread.h>   
#include<time.h>
#include<unistd.h>
#include<string>
using namespace std;

struct ThreadData
{
    RingQueue<Task> *rq;
    string ThreadName;
};

//string opers="+-*/%";

void *Producer(void* args)
{
    ThreadData* td=static_cast<ThreadData*>(args);
    RingQueue<Task> *rq=td->rq;
    string ThreadName=td->ThreadName;

    while(true)
    {
        int data1=rand()%100;
        int data2=rand()%100;
        char oper=opers[rand()%opers.size()];
        Task t(data1,data2,oper);
        rq->Push(t);
        cout<<ThreadName<<" send a task: "<<t.GetTask()<<endl;
        sleep(1);
    }

    delete td;
    return nullptr;
}

void *Consumer(void* args)
{
    ThreadData* td=static_cast<ThreadData*>(args);
    RingQueue<Task> *rq=td->rq;
    string ThreadName=td->ThreadName;

    while(true)
    {
        Task t;
        rq->Pop(t);
        t.run();
        cout<<ThreadName<<" handle a task: "<<t.GetResult()<<endl;
    }

    delete td;
    return nullptr;
}

int main()
{
    srand(time(nullptr)^getpid());
    RingQueue<Task> *rq=new RingQueue<Task>(50);

    pthread_t p[5],c[3];
    for(int i=0;i<5;i++)
    {
        ThreadData* td=new ThreadData;
        td->ThreadName="Producer_"+to_string(i);
        td->rq=rq;

        pthread_create(p+i,nullptr,Producer,(void*)td);
    }

    for(int i=0;i<3;i++)
    {
        ThreadData* td=new ThreadData;
        td->ThreadName="Consumer_"+to_string(i);
        td->rq=rq;

        pthread_create(c+i,nullptr,Consumer,(void*)td);
    }
    
    for(auto x:p)
    {
        pthread_join(x,nullptr);
    }

    for(auto x:c)
    {
        pthread_join(x,nullptr);
    }
    
    delete rq;
    return 0;
}